using System;
using System.Windows;
using System.Windows.Input;

namespace Application
{
    public class MainWindowAdapter : WindowAdapter
    {
        private readonly IMainWindowViewModelFactory _viewModelFactory;
        private bool _isInitialized;

        public MainWindowAdapter(Window wpfWindow, IMainWindowViewModelFactory viewModelFactory)
            : base(wpfWindow)
        {
            if (viewModelFactory == null) throw new ArgumentNullException("viewModelFactory");

            _viewModelFactory = viewModelFactory;
        }

        public override void Show()
        {
            EnsureInitialized();
            base.Show();
        }

        public override void Close()
        {
            EnsureInitialized();
            base.Close();
        }

        public override IWindow CreateChild(object viewModel)
        {
            EnsureInitialized();
            return base.CreateChild(viewModel);
        }

        public override bool? ShowDialog()
        {
            EnsureInitialized();
            return base.ShowDialog();
        }

        private void DeclareKeyBindings(MainWindowViewModel mainWindowViewModel)
        {
            WpfWindow.InputBindings.Add(new KeyBinding(mainWindowViewModel.NewCommand, new KeyGesture(Key.Insert)));
        }

        private void EnsureInitialized()
        {
            if (_isInitialized) return;

            var viewModel = _viewModelFactory.Create(this);
            WpfWindow.DataContext = viewModel;

            DeclareKeyBindings(viewModel);

            _isInitialized = true;
        }
    }
}